# ================================== # Get Service Name from Arguments # ================================== $ServiceName = $args[0] # ================================== # Validate Argument # ================================== if ([string]::IsNullOrWhiteSpace($ServiceName)) { Write-Error "Service name argument is missing." exit 1 } # ================================== # Validate Service Name Characters # ================================== if ($ServiceName -notmatch '^[a-zA-Z0-9_\-\s\.]+$') { Write-Error "Invalid service name." exit 1 } # ================================== # Blocklist of Critical Services # ================================== $BlockedServices = @( "DcomLaunch", "RpcSs", "W32Time", "SamSs", "KeyIso", "VaultSvc", "CryptSvc", "WaaSMedicSvc", "ClipSVC", "AppXSVC", "gpsvc", "wscsvc", "SSDPSRV", "SysMain", "ManageEngine UEMS - Agent", "EventLog", "wuauserv", "MpsSvc", "WinDefend", "BITS", "LanmanWorkstation", "LanmanServer", "Netlogon" ) try { # ================================== # Get Service # ================================== $Service = Get-Service -Name $ServiceName -ErrorAction Stop # ================================== # Check Blocklist # ================================== if ($BlockedServices -contains $Service.DisplayName -or $BlockedServices -contains $Service.Name) { throw "Restart of service '$($Service.DisplayName)' is restricted." } # ================================== # Check Startup Type # ================================== $ServiceInfo = Get-CimInstance Win32_Service ` -Filter "Name='$($Service.Name)'" if ($ServiceInfo.StartMode -eq "Disabled") { throw "Service '$($Service.DisplayName)' is disabled." } # ================================== # Restart Service # ================================== Write-Host "Restarting service: $($Service.DisplayName)" Restart-Service ` -Name $Service.Name ` -ErrorAction Stop $Service.WaitForStatus( [System.ServiceProcess.ServiceControllerStatus]::Running, (New-TimeSpan -Seconds 30) ) Write-Host "Service restarted successfully." } catch { Write-Error $_.Exception.Message exit 1 }